<?php
###
#  Baing PHP 框架 1.0.0
#  http://baing.co/
#
#  Copyright: 白晓阳
#  License: CC BY-NC-SA 4.0
#  https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh
###

namespace bai\resource\document;

use bai\feature\Agent;


class Locale extends \bai\resource\document\Json
{
    public const LOCALE_DEFAULT = 'zh-CN';

    private static $texts = [];

    public static function t(string|array $key, ?array $params = null, string $locale = null): string
    {
        if (!self::$texts || !self::$texts[$locale ?: 'active']) {
            self::setup(['locale' => $locale])?->run();
        }
        $text = Agent::pick($key, self::$texts[$locale] ?? []);
        if (!$text) {
            $text = Agent::pick($key, self::$texts['active'] ?? []) ?? $key;
        }
        if ($params) {
            $text = preg_replace_callback('/:([a-zA-Z0-9]+)/', fn ($matches) => $params[$matches[1]] ?? '', $text);
        }
        return $text;
    }

    protected static function setupId(array &$runtime, string $key = ''): string
    {
        return parent::setupId($runtime, $runtime['locale'] ?? $key);
    }

    public function run()
    {
        $data = parent::run();
        self::$texts[$this->find('locale')] = $data;
        self::$texts['active'] = $data;
        return $data;
    }

    protected function init()
    {
        $this->runtime['locale'] ??= self::LOCALE_DEFAULT;
        $this->runtime['path'] = $this->find('locale') ?: self::LOCALE_DEFAULT;
        parent::init();
    }
}
